# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------



# ----------------------------------------------------------------------------
# CM11a additionnal functions
# Python version 2.7.x and 3.x
# ----------------------------------------------------------------------------
# Software HEYU
# -------------
# - Website: http://www.heyu.org
# - HEYU is used as base for development of scripts
# ----------------------------------------------------------------------------


import logging

logger = logging.getLogger()

RequestCmd = {
   'STAT':(['0x8B','',''],'',14,'Controller status'),
   'ENRI':(['0xEB','0xEB','0x00'],'0x55',1,'Enable Ring Signal'),
   'DIRI':(['0xDB','0xDB','0x00'],'0x55',1,'Disable Ring Signal'),
   }


def ackpwfail(dev):
    """
    After a powerfail, CM11 send continuously Powerfail Signal / Request Set Time 0xA5
    Ack with the signal Timer Download header 0x9B
    """
    logger.debug("%s Ack Powerfail Signal 0xA5.....",dev.idcontroller)
    n = 0
    while n < 5: 
        dev.write('0x9B')
        data = dev.read()
        if data == 0xA5:
            n += 1
        else:
            break
    if n < 5:
        logger.info("%s Powerfail ack successfully",dev.idcontroller)
        return True
    else:
        logger.error("%s Fail to ack Powerfail signal",dev.idcontroller)
        return False


def cm11hf(dev,hf):
    """
    Send a house + function (ON|OFF) code over powerline
    """
    ack = dev.writeack('0x06',hf)
    if ack:
        return True
    else:
        logger.error("Fail to write %s to interface", hf)
        return False

	
def cm11hfd(dev,hf,hd):
    """
    Send a house + function (DIM/BRIGHT) code over powerline
    """
    ack = dev.writeack(hd,hf)
    if ack:
        return True
    else:
        logger.error("Fail to write %s %s to interface", hd, hf)
        return False

	
def cm11hu(dev,hu):
    """
    Send a house + unit code over powerline
    """
    ack = dev.writeack('0x04',hu)
    if ack:
        return True
    else:
        logger.error("Fail to write %s to interface", hu)
        return False


def requestcmd(dev,rcmd):
    if rcmd in RequestCmd:
        seq, ack, lenresp, msg = RequestCmd[rcmd]
        logger.debug("Request %s to controller...",msg)
        dev.write(seq[0])
        r = None
        if seq[1] != '':
            r = dev.readh()
            logger.debug("Check %s - Read %s",seq[1],r)
        if seq[2] != '':
            dev.write(seq[2])
        if ack != '':
            r = dev.readh()
            logger.debug("Ack %s - Read %s",ack,r)
        if lenresp > 1:
            res = []
            for i in range(0,lenresp):
                res.append(dev.readh())
            return res
        return r
    return None


def testwrite(dev):
    logger.debug("Test writing 0x04 0x66 to interface")
    #Send A house code over powerline
    data = dev.writeack('0x04','0x66')
    if not dev.testread(data):
        logger.error("Unable to test CM11a, no reponse from CM11a")
        return False
    return True
